package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"shangyuapi/service"
)

type DaibibuysRBody struct {
	Data       []models.Buyxingbisql `json:"data"`
	PageNo     int                   `json:"pageNo"`
	PageSize   int                   `json:"pageSize"`
	TotalCount int64                 `json:"totalCount"`
	TotalPage  int64                 `json:"totalPage"`
}

type DaibibuysBody struct {
	Phone    string `json:"phone" from:"phone"`
	PageNo   int    `json:"pageNo"`
	Pagesize int    `json:"pagesize"`
	Inttime  int64  `json:"inttime" from:"inttime"`
	Endtime  int64  `json:"endtime" from:"endtime"`
}

func Daibibuys(ctx *gin.Context) {
	request := DaibibuysBody{}
	ctx.ShouldBind(&request)
	endtime := request.Endtime
	inttime := request.Inttime
	phone := request.Phone
	currentPage := request.PageNo
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)

	var miyao string
	miyao = service.Miyao()
	key := []byte(miyao)
	phonejm, _ := service.Encrypt(key, phone)

	var count int64

	var users []models.Buyxingbisql

	res := data_source.Db.Model(&models.Buyxingbi{}).Select("buyxingbi.*, user.phone, user.nickname").Joins("left join user on user.id = buyxingbi.uid").Where("buyxingbi.status = 2")
	if phone != "" {
		res = res.Where("user.phone = ?", phonejm)
	}

	if inttime > 0 {
		res = res.Where("buyxingbi.addtime >= ?", inttime)
	}
	if endtime > 0 {
		res = res.Where("buyxingbi.addtime < ?", endtime+86400)
	}

	res.Model(&models.Buyxingbi{}).Count(&count)

	res.Limit(pageSize).Offset(offsetNum).Order("buyxingbi.id desc").Find(&users)

	for k, v := range users {
		phone1, _ := service.Decrypt(key, v.Phone)
		users[k].Phone = phone1
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := DaibibuysRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}
